import type { ReportList } from './useLoadList'
import type { StatementStore } from './useReportSave'
import { uuid } from '@/utils'
import { useStatementStore } from '@/store'

export default function useReportRow(
  lists: Ref<ReportList[]>,
  rowIndex: Ref<number>,
  option?: {
    callback?: (action: 'del' | 'append' | 'prepend') => any
    createAEmptyRow?: (store: StatementStore) => ReportList
  },
) {
  const statementStore = useStatementStore()
  const { statementFlattenColumns: flattenColumns, setVisible } = statementStore
  const _createAEmptyRow: () => ReportList = () => ({
    uuid: uuid(),
    data: flattenColumns.map(v => ({
      key: v.prop,
      value: '',
      editable: true,
    })),
  })
  const { callback, createAEmptyRow } = option || {}

  function delRow() {
    const index = toValue(rowIndex)
    setVisible(false)
    ElMessageBox.confirm('确定要删除这一行？', '温馨提示')
      .then(() => {
        lists.value.splice(index, 1)
        callback?.('del')
      })
      .catch(() => {})
  }

  function appendRow() {
    const index = toValue(rowIndex)
    const emptyRow = createAEmptyRow ? createAEmptyRow(statementStore) : _createAEmptyRow()
    if (index > -1) {
      lists.value.splice(index + 1, 0, emptyRow)
    }
    setVisible(false)
    callback?.('append')
  }

  function prependRow() {
    const index = toValue(rowIndex)
    const emptyRow = createAEmptyRow ? createAEmptyRow(statementStore) : _createAEmptyRow()
    if (index > -1) {
      lists.value.splice(index, 0, emptyRow)
    }
    setVisible(false)
    callback?.('append')
  }

  return {
    /** 删除 rowIndex 行 */
    delRow,

    /** 在 rowIndex 行后添加一行 */
    appendRow,

    /** 在 rowIndex 行前添加一行 */
    prependRow,
  }
}
